
// 设置cookie
function setCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}

// 获取cookie
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function getURLValue(name) {
    var url = window.location.href.substring(window.location.href.indexOf('?') + 1);
    var split_url = url.split('&');
    for (var i in split_url) {
        var item = split_url[i].split('=');
        if (item[0] == name) {
            return item[1];
        }
    }
    return null;
}

function clearCookies() {
    let cookies = document.cookie.split(";"); // 获取所有 Cookie
    cookies.forEach(cookie => {
    let cookieName = cookie.split("=")[0].trim(); // 获取 Cookie 名称
    document.cookie = cookieName + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
    });
}

function login() {
    var username = document.getElementById('username_input').value;
    var password = document.getElementById('password_input').value;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/userserver/login', true);
    xhr.send(JSON.stringify({
        "username": username,
        "password": password
    }));
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var response = JSON.parse(xhr.responseText);
            console.log(response);
            if (response['status'] == 'ok') {
                setCookie('username', username, 1);
                setCookie('password', password, 1);
                setCookie('seeion_code', response['session_code'], 1);
                document.getElementById('shadow_box').style.display = 'none';
                document.getElementById('login_box').style.display = 'none';
                showRightAlert("登录成功！" , 3000)
                var get_user_info_xhr = new XMLHttpRequest();
                get_user_info_xhr.open('POST', '/userserver/get_user_info', true);
                get_user_info_xhr.send(JSON.stringify({
                    "session_code": getCookie('seeion_code')
                }));
                get_user_info_xhr.onreadystatechange = function() {
                    if (get_user_info_xhr.responseText == '') {
                        return;
                    }
                    console.log(get_user_info_xhr.responseText)
                    var user_info = JSON.parse(get_user_info_xhr.responseText);
                    setCookie('email' , user_info['user_info']['email'], 1)
                }
            }
            else {
                showRightAlert("用户名或密码错误！" , 3000)
            }
        }
    }
}

function goto_email_box() {
    document.getElementById('shadow_box').style.display = 'block';
    document.getElementById('login_email_box').style.display = 'block';
    document.getElementById('login_box').style.display = 'none';
}

function goto_login_box() {
    document.getElementById('shadow_box').style.display = 'block';
    document.getElementById('login_box').style.display = 'block';
    document.getElementById('login_email_box').style.display = 'none';
}

function send_code() {
    var email = document.getElementById('email_input').value;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/userserver/get_captcha', true);
    xhr.send(JSON.stringify({
        "to": email
    }));
    xhr.onreadystatechange = function() {
        console.log(xhr.responseText);
        var json_obj = JSON.parse(xhr.responseText);
        if (json_obj['status'] == 'ok') {
            showRightAlert("验证码已发送至邮箱！" , 3000)
        }
        else {
            showRightAlert("验证码发送失败！" , 3000)
        }
    }
}

function login_by_email() {
    var email = document.getElementById('email_input').value;
    var code = document.getElementById('code_input').value;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/userserver/email_login', true);
    xhr.send(JSON.stringify({
        "email": email,
        "captcha": code
    }));
    xhr.onreadystatechange = function() {
        console.log(xhr.responseText);
        if (xhr.responseText == '') {
            return;
        }
        var json_obj = JSON.parse(xhr.responseText);
        if (json_obj['status'] == 'ok') {
            setCookie('seeion_code', json_obj['session_code'], 1);
            var get_user_info_xhr = new XMLHttpRequest();
                get_user_info_xhr.open('POST', '/userserver/get_user_info', true);
                get_user_info_xhr.send(JSON.stringify({
                    "session_code": getCookie('seeion_code')
                }));
                get_user_info_xhr.onreadystatechange = function() {
                    if (get_user_info_xhr.responseText == '') {
                        return;
                    }
                    console.log(get_user_info_xhr.responseText)
                    var user_info = JSON.parse(get_user_info_xhr.responseText);
                    setCookie('email' , user_info['user_info']['email'], 1)
                }
            document.getElementById('shadow_box').style.display = 'none';
            document.getElementById('login_box').style.display = 'none';
            showRightAlert("登录成功！" , 3000)
        }
        else {
            showRightAlert("验证码错误！" , 3000)
        }
    }
}

window.onload = function() {
    var console_print = document.getElementById('console_print');
    console_print.innerHTML = '';
    var get_code_xhr = new XMLHttpRequest();
    get_code_xhr.open('GET', './js/web-system.js', true);
    get_code_xhr.send();
    get_code_xhr.onreadystatechange = function() {
        var code_array = get_code_xhr.responseText.split('\n');
        var i = 0;
        var code_len = code_array.length;
        console.log("length: "+code_len);
        var loop = setInterval(function() {
            if (i < code_len) {
                i++;
                console_print.innerHTML += code_array[i].replaceAll(' ', '&nbsp;') + '<br>';
                console_print.scrollTop = console_print.scrollHeight;
                return;
            }
            if (i >= code_len) { 
                i = 0;
                return;
            }
        } , 100);
        setInterval(function() {
            console_print.innerHTML = console_print.innerHTML.substring(console_print.innerHTML.length - 1000);
        } , 100000);
    }
    var seeion_code = getCookie('seeion_code');
    if (seeion_code == null) {
        document.getElementById('shadow_box').style.display = 'block';
        document.getElementById('login_box').style.display = 'block';
    }
    else {
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/userserver/check_login_code', true);
        xhr.send(JSON.stringify({
            "session_code": getCookie('seeion_code')
        }));
        xhr.onreadystatechange = function() {
            if (xhr.responseText == '') {
                return;
            }
            var response = JSON.parse(xhr.responseText);
            if (response['status'] == 'ok') {
                var get_user_info_xhr = new XMLHttpRequest();
                get_user_info_xhr.open('POST', '/userserver/get_user_info', true);
                get_user_info_xhr.send(JSON.stringify({
                    "session_code": getCookie('seeion_code')
                }));
                get_user_info_xhr.onreadystatechange = function() {
                    if (get_user_info_xhr.responseText == '') {
                        return;
                    }
                    console.log(get_user_info_xhr.responseText)
                    var user_info = JSON.parse(get_user_info_xhr.responseText);
                    setCookie('email' , user_info['user_info']['email'], 1)
                }

                document.getElementById('shadow_box').style.display = 'none';
                document.getElementById('login_box').style.display = 'none';
                
                showRightAlert("登录成功！" , 3000)

            }
            else {
                clearCookies();
                showRightAlert("请先登录！" , 3000);
                document.getElementById('shadow_box').style.display = 'block';
                document.getElementById('login_box').style.display = 'block';
            }
        }
    }
}